package com.cs.common.encryption;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.security.SecureRandom;

public class DESEncryptDecrypt {
    private static String algorithm = "AES";
    private static String charset = "utf-8";

    public static String encode(String content, String key) {
        try {
            Cipher cipher = getCipher(key, Cipher.ENCRYPT_MODE);
            byte[] resBytes = content.getBytes(charset);
            return parseByte2HexStr(cipher.doFinal(resBytes));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String decode(String content, String key) {
        try {
            Cipher cipher = getCipher(key, Cipher.DECRYPT_MODE);
            return new String(cipher.doFinal(parseHexStr2Byte(content)));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Cipher getCipher(String key, int mode) throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance(algorithm);
        byte[] keyBytes = key.getBytes(charset);
        keyGenerator.init(new SecureRandom(keyBytes));
        SecretKey secretKey = keyGenerator.generateKey();
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(), algorithm);
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(mode, secretKeySpec);
        return cipher;
    }

    private static String parseByte2HexStr(byte buf[]) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1)
            return null;
        byte[] result = new byte[hexStr.length()/2];
        for (int i = 0;i< hexStr.length()/2; i++) {
            int high = Integer.parseInt(hexStr.substring(i*2, i*2+1), 16);
            int low = Integer.parseInt(hexStr.substring(i*2+1, i*2+2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }

}
